<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Example: Attribute Getters, Setters and Validators</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <script src="../../build/yui/yui-min.js"></script>
</head>
<body>

<div id="doc">
    <h1>Example: Attribute Getters, Setters and Validators</h1>

    

    <div class="yui3-g">
        <div id="main" class="yui3-u">
            <div class="content"><style type="text/css" scoped>

    #boxParent {
        overflow:hidden;
        background-color:#004c6d;
        height:25em;
        padding:10px;
        margin:5px;
    }

    #boxParent .yui3-box p, #attrs p {
        margin:2px;
    }

    .attrs {
        border:1px solid #000;
        background-color:#cdcdcd;
        margin:5px;
    }

    .attrs .header {
        font-weight:bold;
        background-color:#aaa;
        padding:5px;
    }

    .attrs .body {
        padding:10px;
    }
 
    .attrs .body .hints li {
        padding-bottom:10px;
    }

    .attrs .footer {
        padding:0px 20px 10px 20px;
    }

    .attrs label {
        font-weight:bold;
        display:block;
        float:left;
        width:4em;
    }

    .attrs .hint {
        font-size:85%;
        color: #004c6d;
    }

    .attrs .fields {
        border-top:1px solid #aaa;
        padding:10px;
    }

    .yui3-box {
        padding:5px;
        border:1px solid #000;
        width:8em;
        height:8em;
        text-align:center;
        color:#000;
    }

    .yui3-box .color, .yui3-box .coord {
        font-family:courier;
    }

</style>

<div class="intro">
    <p>The <a href="attribute-basic.html">"Basic Attribute Configuration" example</a> shows how you can add attributes to a host class, and set up default values for them using the attribute configuration object. This example explores how you can configure <code>setter</code>, <code>getter</code> and <code>validator</code> functions for individual attributes, which can be used to modify or normalize attribute values during get and set invocations, and prevent invalid values from being stored.</p> 
</div>

<div class="example">
    <div id="attrs" class="attrs">
    <div class="header">Enter new values and click the "Set" buttons</div>
    <div class="body">
        <ul class="hints">
            <li>Try entering valid and invalid values for x, y; or values which attempt to position the box outside it's parent (parent box co-ordinates are displayed next to the text box).</li>
            <li>Try entering rgb, hex or keyword color values [ <code>rgb(255,0,0)</code>, <code>#ff0000</code>, <code>red</code> ].</li>
        </ul>
        <div class="fields">
            <p>
                <label for="x">x:</label>
                <input type="text" name="x" id="x" />
                <button type="button" class="action" id="setX">Set</button>
                <span id="xhint" class="hint"></span>
            </p>
            <p>
                <label for="y">y:</label>
                <input type="text" name="y" id="y" />
                <button type="button" class="action" id="setY">Set</button>
                <span id="yhint" class="hint"></span>
            </p>
            <p>
                <label for="color">color:</label>
                <input type="text" name="color" id="color" />
                <button type="button" class="action" id="setColor">Set</button>
            </p>
        </div>
    </div>
    <div class="footer">
        <button type="button" class="action" id="setXY">Set XY</button>
        <button type="button" class="action" id="setAll">Set All</button>
        <button type="button" class="action" id="getAll">Get All</button>
    </div>
</div>

<div id="boxParent"></div>

<script type="text/javascript">
// Get a new YUI instance 
YUI().use("node", "attribute", function(Y) {

    var boxParent = Y.one("#boxParent");

    // Setup a custom class with attribute support
    function Box(cfg) {
        this._createNode(cfg);
        
        // Attribute configuration
        var attrs = {
    
            "parent" : {
                value: null
            },

            "x" : {
                setter: function(val, name) {
                    // Pass through x value to xy
                    this.set("xy", [parseInt(val), this.get("y")]);
                },
    
                getter: function(val, name) {
                    // Get x value from xy
                    return this.get("xy")[0];
                }
            },
    
            "y" : {
                setter: function(val, name) {
                    // Pass through y value to xy
                    this.set("xy", [this.get("x"), parseInt(val)]);
                },
    
                getter: function() {
                    // Get y value from xy
                    return this.get("xy")[1];
                }
            },
    
            "xy" : {
                // Actual stored xy co-ordinates
                value: [0, 0],
    
                setter: function(val, name) {
                    // Constrain XY value to the parent element.
    
                    // Returns the constrained xy value, which will
                    // be the final value stored.
                    return this.constrain(val);
                },
    
                validator: function(val, name) {
                    // Ensure we only store a valid data value
                    return (Y.Lang.isArray(val) && val.length == 2 && Y.Lang.isNumber(val[0]) && Y.Lang.isNumber(val[1]));
                }
            },
    
            "color" : {
                value: "olive",
    
                getter: function(val, name) {
                    // Always normalize the returned value to 
                    // a hex color value,  even if the stored 
                    // value is a keyword, or an rgb value.
                    if (val) {
                        return Y.Color.toHex(val);
                    } else {
                        return null;
                    }
                },
    
                validator: function(val, name) {
                    // Ensure we only store rgb, hex or keyword values.
                    return (Y.Color.re_RGB.test(val) || Y.Color.re_hex.test(val) || Y.Color.KEYWORDS[val]); 
                }
            }
        };

        this.addAttrs(attrs, cfg);

        this._sync();
        this._bind();
    }

    Box.BUFFER = 5;

    // Create the box node
    Box.prototype._createNode = function() {
        this._node = Y.Node.create('<div class="yui3-box"><p>Positioned Box</p><p class="coord"></p><p class="color">None</p></div>');
    };

    // Update rendered state to match the attribute state
    Box.prototype._sync = function() {
        this._syncParent();
        this._syncXY();
        this._syncColor();
    };

    Box.prototype._syncParent = function() {
        this.get("parent").appendChild(this._node);
    };

    Box.prototype._syncXY = function() {
        this._node.setXY(this.get("xy"));
        this._node.one("p.coord").set("innerHTML", "[" + this.get("x") + "," + this.get("y") + "]");
    };

    Box.prototype._syncColor = function() {
        this._node.setStyle("backgroundColor", this.get("color"));
        this._node.one("p.color").set("innerHTML", this.get("color"));
    };

    // Bind listeners for attribute change events
    Box.prototype._bind = function() {

        // Reflect any changes in xy, to the rendered Node
        this.after("xyChange", this._syncXY);

        // Reflect any changes in color, to the rendered Node
        // and output the color value received from get
        this.after("colorChange", this._syncColor);

        // Append the rendered node to the parent provided
        this.after("parentChange", this._syncParent);

    };

    // Get min, max unconstrained values for X. Using Math.round to handle FF3's sub-pixel region values
    Box.prototype.getXConstraints = function() {
        var parentRegion = this.get("parent").get("region");
        return [Math.round(parentRegion.left + Box.BUFFER), Math.round(parentRegion.right - this._node.get("offsetWidth") - Box.BUFFER)];
    };

    // Get min, max unconstrained values for Y.  Using Math.round to handle FF3's sub-pixel region values
    Box.prototype.getYConstraints = function() {
        var parentRegion = this.get("parent").get("region");
        return [Math.round(parentRegion.top + Box.BUFFER), Math.round(parentRegion.bottom - this._node.get("offsetHeight") - Box.BUFFER)];
    };

    // Constrain the x,y value provided
    Box.prototype.constrain = function(val) {

        // If the X value places the box outside it's parent,
        // modify it's value to place the box inside it's parent.

        var xConstraints = this.getXConstraints();

        if (val[0] < xConstraints[0]) {
            val[0] = xConstraints[0];
        } else {
            if (val[0] > xConstraints[1]) {
                val[0] = xConstraints[1];
            }
        }

        // If the Y value places the box outside it's parent,
        // modify it's value to place the box inside it's parent.

        var yConstraints = this.getYConstraints();

        if (val[1] < yConstraints[0]) {
            val[1] = yConstraints[0];
        } else {
            if (val[1] > yConstraints[1]) {
                val[1] = yConstraints[1];
            }
        }

        return val;
    };


    Y.augment(Box, Y.Attribute);

    // ------

    // Create a new instance of Box
    var box = new Box({
        parent : boxParent 
    });

    // Set references to form controls
    var xTxt = Y.one("#x");
    var yTxt = Y.one("#y");
    var colorTxt = Y.one("#color");

    var xHint = Y.one("#xhint");
    var yHint = Y.one("#yhint");

    function getAll() {
        xTxt.set("value", box.get("x"));
        yTxt.set("value", box.get("y"));
        colorTxt.set("value", box.get("color"));
    }

    // Bind DOM events for Form Controls

    // Use event delegation for the action button clicks
    Y.delegate("click", function(e) {

        // Get Node target from the event object

        // We already know it's a button which has an action because
        // of our selector (button.action), so all we need to do is 
        // route it based on the id.
        var id = e.currentTarget.get("id");

        switch (id) {
            case "setXY":
                box.set("xy", [parseInt(xTxt.get("value")), parseInt(yTxt.get("value"))]);
                break;
            case "setX":
                box.set("x", parseInt(xTxt.get("value")));
                break;
            case "setY":
                box.set("y", parseInt(yTxt.get("value")));
                break;
            case "setColor":
                box.set("color", Y.Lang.trim(colorTxt.get("value")));
                break;
            case "setAll":
                box.set("xy", [parseInt(xTxt.get("value")), parseInt(yTxt.get("value"))]);
                box.set("color", Y.Lang.trim(colorTxt.get("value")));
                break;
            case "getAll":
                getAll();
                break;
            default:
                break;
        }

    }, "#attrs", "button.action");

    // Bind listeners to provide min, max unconstrained value hints for x, y
    // (focus/blur doesn't bubble, so bind individual listeners)
    Y.on("focus", function() {
        var minmax = box.getXConstraints();
        xHint.set("innerHTML", "Valid values: " + minmax[0] + " to " + minmax[1]);
    }, xTxt);

    Y.on("focus", function() {
        var minmax = box.getYConstraints();
        yHint.set("innerHTML", "Valid values: " + minmax[0] + " to " + minmax[1]);
    }, yTxt);

    Y.on("blur", function() {
        xHint.set("innerHTML", "");
    }, xTxt);

    Y.on("blur", function() {
        yHint.set("innerHTML", "");
    }, yTxt);

    getAll();
});
</script>

</div>

<h2>Getter, Setter And Validator Functions</h2>

<p>Attribute lets you configure <code>getter</code> and <code>setter</code> functions for each attribute. These functions are invoked when the user calls Attribute's <code>get</code> and <code>set</code> methods, and provide a way to modify the value returned or the value stored respectively.</p>

<p>You can also define a <code>validator</code> function for each attribute, which is used to validate the final value before it gets stored.</p>

<p>All these functions receive the value and name of the attribute being set or retrieved, as shown in the example code below. The name is not used in this example, but is provided to support use cases where you may wish to share the same function between different attributes.</p>

<h3>Creating The Box Class - The X, Y And XY Attributes</h3>

<p>In this example, we'll set up a custom <code>Box</code> class representing a positionable element, with <code>x</code>, <code>y</code> and <code>xy</code> attributes.</p>

<p>Only the <code>xy</code> attribute will actually store the page co-ordinate position of the box. The <code>x</code> and <code>y</code> attributes provide the user a convenient way to set only one of the co-ordinates. 
However we don't want to store the actual values in the <code>x</code> and <code>y</code> attributes, to avoid having to constantly synchronize all three. 

The <code>getter</code> and <code>setter</code> functions provide us with an easy way to achieve this. We'll define <code>getter</code> and <code>setter</code> functions for both the <code>x</code> and <code>y</code> attributes, which simply pass through to the <code>xy</code> attribute to store and retrieve values:</p>

<pre class="code prettyprint">&#x2F;&#x2F; Setup a custom class with attribute support
function Box(cfg) {

    ...
          
    &#x2F;&#x2F; Attribute configuration
    var attrs = {

        &quot;parent&quot; : {
            value: null
        },

        &quot;x&quot; : {
            setter: function(val, name) {
                &#x2F;&#x2F; Pass through x value to xy
                this.set(&quot;xy&quot;, [parseInt(val), this.get(&quot;y&quot;)]);
            },

            getter: function(val, name) {
                &#x2F;&#x2F; Get x value from xy
                return this.get(&quot;xy&quot;)[0];
            }
        },

        &quot;y&quot; : {
            setter: function(val, name) {
                &#x2F;&#x2F; Pass through y value to xy
                this.set(&quot;xy&quot;, [this.get(&quot;x&quot;), parseInt(val)]);
            },

            getter: function() {
                &#x2F;&#x2F; Get y value from xy
                return this.get(&quot;xy&quot;)[1];
            }
        },

        &quot;xy&quot; : {
            &#x2F;&#x2F; Actual stored xy co-ordinates
            value: [0, 0],

            setter: function(val, name) {
                &#x2F;&#x2F; Constrain XY value to the parent element.

                &#x2F;&#x2F; Returns the constrained xy value, which will
                &#x2F;&#x2F; be the final value stored.
                return this.constrain(val);
            },

            validator: function(val, name) {
                &#x2F;&#x2F; Ensure we only store a valid data value
                return (Y.Lang.isArray(val) &amp;&amp; 
                        val.length == 2 &amp;&amp; 
                        Y.Lang.isNumber(val[0]) &amp;&amp; Y.Lang.isNumber(val[1]));
            }
        },

    ...

    this.addAttrs(attrs, cfg);

    ...
}</pre>


<p>The <code>validator</code> function for <code>xy</code> ensures that only valid values finally end up being stored.</p>

<p>The <code>xy</code> attribute also has a <code>setter</code> function configured, which makes sure that the box is always constrained to it's parent element. The <code>constrain</code> method which it delegates to, takes the xy value the user is trying to set and returns a constrained value if the x or y values fall outside the parent box. The value which is returned by the <code>setter</code> is the value which is ultimately stored for the <code>xy</code> attribute:</p>

<pre class="code prettyprint">&#x2F;&#x2F; Get min, max unconstrained values for X. 
&#x2F;&#x2F; Using Math.round to handle FF3&#x27;s sub-pixel region values
Box.prototype.getXConstraints = function() {
    var parentRegion = this.get(&quot;parent&quot;).get(&quot;region&quot;);
    return [Math.round(parentRegion.left + Box.BUFFER), 
            Math.round(parentRegion.right - this._node.get(&quot;offsetWidth&quot;) - Box.BUFFER)];
};

&#x2F;&#x2F; Get min, max unconstrained values for Y.  
&#x2F;&#x2F; Using Math.round to handle FF3&#x27;s sub-pixel region values
Box.prototype.getYConstraints = function() {
    var parentRegion = this.get(&quot;parent&quot;).get(&quot;region&quot;);
    return [Math.round(parentRegion.top + Box.BUFFER), 
            Math.round(parentRegion.bottom - this._node.get(&quot;offsetHeight&quot;) - Box.BUFFER)];
};

&#x2F;&#x2F; Constrains given x,y values
Box.prototype.constrain = function(val) {

    &#x2F;&#x2F; If the X value places the box outside it&#x27;s parent,
    &#x2F;&#x2F; modify it&#x27;s value to place the box inside it&#x27;s parent.

    var xConstraints = this.getXConstraints();

    if (val[0] &lt; xConstraints[0]) {
        val[0] = xConstraints[0];
    } else {
        if (val[0] &gt; xConstraints[1]) {
            val[0] = xConstraints[1];
        }
    }

    &#x2F;&#x2F; If the Y value places the box outside it&#x27;s parent,
    &#x2F;&#x2F; modify it&#x27;s value to place the box inside it&#x27;s parent.

    var yConstraints = this.getYConstraints();

    if (val[1] &lt; yConstraints[0]) {
        val[1] = yConstraints[0];
    } else {
        if (val[1] &gt; yConstraints[1]) {
            val[1] = yConstraints[1];
        }
    }

    return val;
};</pre>


<p>The <code>setter</code>, <code>getter</code> and <code>validator</code> functions are invoked with the host object as the context, so that they can refer to the host object using "<code>this</code>", as we see in the <code>setter</code> function for <code>xy</code>.</p>

<h3>The Color Attribute - Normalizing Stored Values Through Get</h3>

<p>The <code>Box</code> class also has a <code>color</code> attribute which also has a <code>getter</code> and <code>validator</code> functions defined:</p>

<pre class="code prettyprint">...
&quot;color&quot; : {
    value: &quot;olive&quot;,

    getter: function(val, name) {
        if (val) {
            return Y.Color.toHex(val);
        } else {
            return null;
        }
    },

    validator: function(val, name) {
        return (Y.Color.re_RGB.test(val) || Y.Color.re_hex.test(val) 
                    || Y.Color.KEYWORDS[val]);
    }
}
...</pre>


<p>The role of the <code>getter</code> handler in this case is to normalize the actual stored value of the <code>color</code> attribute, so that users always receive the hex value, regardless of the actual value stored, which maybe a color keyword (e.g. <code>&quot;red&quot;</code>), an rgb value (e.g.<code>rbg(255,0,0)</code>), or a hex value (<code>#ff0000</code>). The <code>validator</code> ensures the the stored value is one of these three formats.</p>

<h3>Syncing Changes Using Attribute Change Events</h3>

<p>Another interesting aspect of this example, is it's use of attribute change events to listen for changes to the attribute values. <code>Box</code>'s <code>_bind</code> method configures a set of attribute change event listeners which monitor changes to the <code>xy</code>, <code>color</code> and <code>parent</code> attributes and update the rendered DOM for the Box in response:</p>

<pre class="code prettyprint">&#x2F;&#x2F; Bind listeners for attribute change events
Box.prototype._bind = function() {

    &#x2F;&#x2F; Reflect any changes in xy, to the rendered Node
    this.after(&quot;xyChange&quot;, this._syncXY);

    &#x2F;&#x2F; Reflect any changes in color, to the rendered Node
    &#x2F;&#x2F; and output the color value received from get
    this.after(&quot;colorChange&quot;, this._syncColor);

    &#x2F;&#x2F; Append the rendered node to the parent provided
    this.after(&quot;parentChange&quot;, this._syncParent);

};</pre>


<p>Since only <code>xy</code> stores the final co-ordinates, we don't need to monitor the <code>x</code> and <code>y</code> attributes individually for changes.</p>

<h3>DOM Event Listeners And Delegation</h3>

<p>Although not an integral part of the example, it's worth highlighting the code which is used to setup the DOM event listeners for the form elements used by the example:</p>

<pre class="code prettyprint">&#x2F;&#x2F; Set references to form controls
var xTxt = Y.one(&quot;#x&quot;);
var yTxt = Y.one(&quot;#y&quot;);
var colorTxt = Y.one(&quot;#color&quot;);

&#x2F;&#x2F; Use event delegation for the action button clicks
Y.delegate(&quot;click&quot;, function(e) {

    &#x2F;&#x2F; Get Node target from the event object. 

    &#x2F;&#x2F; We already know it&#x27;s a button which has an action because
    &#x2F;&#x2F; of our selector (button.action), so all we need to do is 
    &#x2F;&#x2F; route it based on the id.
    var id = e.currentTarget.get(&quot;id&quot;);

    switch (id) {
        case &quot;setXY&quot;:
            box.set(&quot;xy&quot;, [parseInt(xTxt.get(&quot;value&quot;)), parseInt(yTxt.get(&quot;value&quot;))]);
            break;
        case &quot;setX&quot;:
            box.set(&quot;x&quot;, parseInt(xTxt.get(&quot;value&quot;)));
            break;
        case &quot;setY&quot;:
            box.set(&quot;y&quot;, parseInt(yTxt.get(&quot;value&quot;)));
            break;
        case &quot;setColor&quot;:
            box.set(&quot;color&quot;, Y.Lang.trim(colorTxt.get(&quot;value&quot;)));
            break;
        case &quot;setAll&quot;:
            box.set(&quot;xy&quot;, [parseInt(xTxt.get(&quot;value&quot;)), parseInt(yTxt.get(&quot;value&quot;))]);
            box.set(&quot;color&quot;, Y.Lang.trim(colorTxt.get(&quot;value&quot;)));
            break;
        case &quot;getAll&quot;:
            getAll();
            break;
        default:
            break;
    }

}, &quot;#attrs&quot;, &quot;click&quot;, &quot;button.action&quot;);</pre>


<p>Rather than attach individual listeners to each button, the above code uses YUI 3's <code>delegate</code> support, to listen for clicks from <code>buttons</code> with an <code>action</code> class which bubble up to the <code>attrs</code> element.</p>
<p>The delegate listener uses the <a href="http://yuilibrary.com/yui/docs/api/DOMEventFacade.html">Event Facade</a> which normalizes cross-browser access to DOM event properties, such as <code>currentTarget</code>, to route to the appropriate button handler. Note the use of selector syntax when we specify the elements for the listener (e.g. <code>#attrs</code>, <code>button.actions</code>) and the use of the <a href="http://yuilibrary.com/yui/docs/api/Node.html">Node</a> facade when dealing with references to HTML elements (e.g. <code>xTxt, yTxt, colorTxt</code>).</p>

<h2>Complete Example Source</h2>

<pre class="code prettyprint">&lt;div id=&quot;attrs&quot; class=&quot;attrs&quot;&gt;
    &lt;div class=&quot;header&quot;&gt;Enter new values and click the &quot;Set&quot; buttons&lt;&#x2F;div&gt;
    &lt;div class=&quot;body&quot;&gt;
        &lt;ul class=&quot;hints&quot;&gt;
            &lt;li&gt;Try entering valid and invalid values for x, y; or values which attempt to position the box outside it&#x27;s parent (parent box co-ordinates are displayed next to the text box).&lt;&#x2F;li&gt;
            &lt;li&gt;Try entering rgb, hex or keyword color values [ &lt;code&gt;rgb(255,0,0)&lt;&#x2F;code&gt;, &lt;code&gt;#ff0000&lt;&#x2F;code&gt;, &lt;code&gt;red&lt;&#x2F;code&gt; ].&lt;&#x2F;li&gt;
        &lt;&#x2F;ul&gt;
        &lt;div class=&quot;fields&quot;&gt;
            &lt;p&gt;
                &lt;label for=&quot;x&quot;&gt;x:&lt;&#x2F;label&gt;
                &lt;input type=&quot;text&quot; name=&quot;x&quot; id=&quot;x&quot; &#x2F;&gt;
                &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;setX&quot;&gt;Set&lt;&#x2F;button&gt;
                &lt;span id=&quot;xhint&quot; class=&quot;hint&quot;&gt;&lt;&#x2F;span&gt;
            &lt;&#x2F;p&gt;
            &lt;p&gt;
                &lt;label for=&quot;y&quot;&gt;y:&lt;&#x2F;label&gt;
                &lt;input type=&quot;text&quot; name=&quot;y&quot; id=&quot;y&quot; &#x2F;&gt;
                &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;setY&quot;&gt;Set&lt;&#x2F;button&gt;
                &lt;span id=&quot;yhint&quot; class=&quot;hint&quot;&gt;&lt;&#x2F;span&gt;
            &lt;&#x2F;p&gt;
            &lt;p&gt;
                &lt;label for=&quot;color&quot;&gt;color:&lt;&#x2F;label&gt;
                &lt;input type=&quot;text&quot; name=&quot;color&quot; id=&quot;color&quot; &#x2F;&gt;
                &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;setColor&quot;&gt;Set&lt;&#x2F;button&gt;
            &lt;&#x2F;p&gt;
        &lt;&#x2F;div&gt;
    &lt;&#x2F;div&gt;
    &lt;div class=&quot;footer&quot;&gt;
        &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;setXY&quot;&gt;Set XY&lt;&#x2F;button&gt;
        &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;setAll&quot;&gt;Set All&lt;&#x2F;button&gt;
        &lt;button type=&quot;button&quot; class=&quot;action&quot; id=&quot;getAll&quot;&gt;Get All&lt;&#x2F;button&gt;
    &lt;&#x2F;div&gt;
&lt;&#x2F;div&gt;

&lt;div id=&quot;boxParent&quot;&gt;&lt;&#x2F;div&gt;

&lt;script type=&quot;text&#x2F;javascript&quot;&gt;
&#x2F;&#x2F; Get a new YUI instance 
YUI().use(&quot;node&quot;, &quot;attribute&quot;, function(Y) {

    var boxParent = Y.one(&quot;#boxParent&quot;);

    &#x2F;&#x2F; Setup a custom class with attribute support
    function Box(cfg) {
        this._createNode(cfg);
        
        &#x2F;&#x2F; Attribute configuration
        var attrs = {
    
            &quot;parent&quot; : {
                value: null
            },

            &quot;x&quot; : {
                setter: function(val, name) {
                    &#x2F;&#x2F; Pass through x value to xy
                    this.set(&quot;xy&quot;, [parseInt(val), this.get(&quot;y&quot;)]);
                },
    
                getter: function(val, name) {
                    &#x2F;&#x2F; Get x value from xy
                    return this.get(&quot;xy&quot;)[0];
                }
            },
    
            &quot;y&quot; : {
                setter: function(val, name) {
                    &#x2F;&#x2F; Pass through y value to xy
                    this.set(&quot;xy&quot;, [this.get(&quot;x&quot;), parseInt(val)]);
                },
    
                getter: function() {
                    &#x2F;&#x2F; Get y value from xy
                    return this.get(&quot;xy&quot;)[1];
                }
            },
    
            &quot;xy&quot; : {
                &#x2F;&#x2F; Actual stored xy co-ordinates
                value: [0, 0],
    
                setter: function(val, name) {
                    &#x2F;&#x2F; Constrain XY value to the parent element.
    
                    &#x2F;&#x2F; Returns the constrained xy value, which will
                    &#x2F;&#x2F; be the final value stored.
                    return this.constrain(val);
                },
    
                validator: function(val, name) {
                    &#x2F;&#x2F; Ensure we only store a valid data value
                    return (Y.Lang.isArray(val) &amp;&amp; val.length == 2 &amp;&amp; Y.Lang.isNumber(val[0]) &amp;&amp; Y.Lang.isNumber(val[1]));
                }
            },
    
            &quot;color&quot; : {
                value: &quot;olive&quot;,
    
                getter: function(val, name) {
                    &#x2F;&#x2F; Always normalize the returned value to 
                    &#x2F;&#x2F; a hex color value,  even if the stored 
                    &#x2F;&#x2F; value is a keyword, or an rgb value.
                    if (val) {
                        return Y.Color.toHex(val);
                    } else {
                        return null;
                    }
                },
    
                validator: function(val, name) {
                    &#x2F;&#x2F; Ensure we only store rgb, hex or keyword values.
                    return (Y.Color.re_RGB.test(val) || Y.Color.re_hex.test(val) || Y.Color.KEYWORDS[val]); 
                }
            }
        };

        this.addAttrs(attrs, cfg);

        this._sync();
        this._bind();
    }

    Box.BUFFER = 5;

    &#x2F;&#x2F; Create the box node
    Box.prototype._createNode = function() {
        this._node = Y.Node.create(&#x27;&lt;div class=&quot;yui3-box&quot;&gt;&lt;p&gt;Positioned Box&lt;&#x2F;p&gt;&lt;p class=&quot;coord&quot;&gt;&lt;&#x2F;p&gt;&lt;p class=&quot;color&quot;&gt;None&lt;&#x2F;p&gt;&lt;&#x2F;div&gt;&#x27;);
    };

    &#x2F;&#x2F; Update rendered state to match the attribute state
    Box.prototype._sync = function() {
        this._syncParent();
        this._syncXY();
        this._syncColor();
    };

    Box.prototype._syncParent = function() {
        this.get(&quot;parent&quot;).appendChild(this._node);
    };

    Box.prototype._syncXY = function() {
        this._node.setXY(this.get(&quot;xy&quot;));
        this._node.one(&quot;p.coord&quot;).set(&quot;innerHTML&quot;, &quot;[&quot; + this.get(&quot;x&quot;) + &quot;,&quot; + this.get(&quot;y&quot;) + &quot;]&quot;);
    };

    Box.prototype._syncColor = function() {
        this._node.setStyle(&quot;backgroundColor&quot;, this.get(&quot;color&quot;));
        this._node.one(&quot;p.color&quot;).set(&quot;innerHTML&quot;, this.get(&quot;color&quot;));
    };

    &#x2F;&#x2F; Bind listeners for attribute change events
    Box.prototype._bind = function() {

        &#x2F;&#x2F; Reflect any changes in xy, to the rendered Node
        this.after(&quot;xyChange&quot;, this._syncXY);

        &#x2F;&#x2F; Reflect any changes in color, to the rendered Node
        &#x2F;&#x2F; and output the color value received from get
        this.after(&quot;colorChange&quot;, this._syncColor);

        &#x2F;&#x2F; Append the rendered node to the parent provided
        this.after(&quot;parentChange&quot;, this._syncParent);

    };

    &#x2F;&#x2F; Get min, max unconstrained values for X. Using Math.round to handle FF3&#x27;s sub-pixel region values
    Box.prototype.getXConstraints = function() {
        var parentRegion = this.get(&quot;parent&quot;).get(&quot;region&quot;);
        return [Math.round(parentRegion.left + Box.BUFFER), Math.round(parentRegion.right - this._node.get(&quot;offsetWidth&quot;) - Box.BUFFER)];
    };

    &#x2F;&#x2F; Get min, max unconstrained values for Y.  Using Math.round to handle FF3&#x27;s sub-pixel region values
    Box.prototype.getYConstraints = function() {
        var parentRegion = this.get(&quot;parent&quot;).get(&quot;region&quot;);
        return [Math.round(parentRegion.top + Box.BUFFER), Math.round(parentRegion.bottom - this._node.get(&quot;offsetHeight&quot;) - Box.BUFFER)];
    };

    &#x2F;&#x2F; Constrain the x,y value provided
    Box.prototype.constrain = function(val) {

        &#x2F;&#x2F; If the X value places the box outside it&#x27;s parent,
        &#x2F;&#x2F; modify it&#x27;s value to place the box inside it&#x27;s parent.

        var xConstraints = this.getXConstraints();

        if (val[0] &lt; xConstraints[0]) {
            val[0] = xConstraints[0];
        } else {
            if (val[0] &gt; xConstraints[1]) {
                val[0] = xConstraints[1];
            }
        }

        &#x2F;&#x2F; If the Y value places the box outside it&#x27;s parent,
        &#x2F;&#x2F; modify it&#x27;s value to place the box inside it&#x27;s parent.

        var yConstraints = this.getYConstraints();

        if (val[1] &lt; yConstraints[0]) {
            val[1] = yConstraints[0];
        } else {
            if (val[1] &gt; yConstraints[1]) {
                val[1] = yConstraints[1];
            }
        }

        return val;
    };


    Y.augment(Box, Y.Attribute);

    &#x2F;&#x2F; ------

    &#x2F;&#x2F; Create a new instance of Box
    var box = new Box({
        parent : boxParent 
    });

    &#x2F;&#x2F; Set references to form controls
    var xTxt = Y.one(&quot;#x&quot;);
    var yTxt = Y.one(&quot;#y&quot;);
    var colorTxt = Y.one(&quot;#color&quot;);

    var xHint = Y.one(&quot;#xhint&quot;);
    var yHint = Y.one(&quot;#yhint&quot;);

    function getAll() {
        xTxt.set(&quot;value&quot;, box.get(&quot;x&quot;));
        yTxt.set(&quot;value&quot;, box.get(&quot;y&quot;));
        colorTxt.set(&quot;value&quot;, box.get(&quot;color&quot;));
    }

    &#x2F;&#x2F; Bind DOM events for Form Controls

    &#x2F;&#x2F; Use event delegation for the action button clicks
    Y.delegate(&quot;click&quot;, function(e) {

        &#x2F;&#x2F; Get Node target from the event object

        &#x2F;&#x2F; We already know it&#x27;s a button which has an action because
        &#x2F;&#x2F; of our selector (button.action), so all we need to do is 
        &#x2F;&#x2F; route it based on the id.
        var id = e.currentTarget.get(&quot;id&quot;);

        switch (id) {
            case &quot;setXY&quot;:
                box.set(&quot;xy&quot;, [parseInt(xTxt.get(&quot;value&quot;)), parseInt(yTxt.get(&quot;value&quot;))]);
                break;
            case &quot;setX&quot;:
                box.set(&quot;x&quot;, parseInt(xTxt.get(&quot;value&quot;)));
                break;
            case &quot;setY&quot;:
                box.set(&quot;y&quot;, parseInt(yTxt.get(&quot;value&quot;)));
                break;
            case &quot;setColor&quot;:
                box.set(&quot;color&quot;, Y.Lang.trim(colorTxt.get(&quot;value&quot;)));
                break;
            case &quot;setAll&quot;:
                box.set(&quot;xy&quot;, [parseInt(xTxt.get(&quot;value&quot;)), parseInt(yTxt.get(&quot;value&quot;))]);
                box.set(&quot;color&quot;, Y.Lang.trim(colorTxt.get(&quot;value&quot;)));
                break;
            case &quot;getAll&quot;:
                getAll();
                break;
            default:
                break;
        }

    }, &quot;#attrs&quot;, &quot;button.action&quot;);

    &#x2F;&#x2F; Bind listeners to provide min, max unconstrained value hints for x, y
    &#x2F;&#x2F; (focus&#x2F;blur doesn&#x27;t bubble, so bind individual listeners)
    Y.on(&quot;focus&quot;, function() {
        var minmax = box.getXConstraints();
        xHint.set(&quot;innerHTML&quot;, &quot;Valid values: &quot; + minmax[0] + &quot; to &quot; + minmax[1]);
    }, xTxt);

    Y.on(&quot;focus&quot;, function() {
        var minmax = box.getYConstraints();
        yHint.set(&quot;innerHTML&quot;, &quot;Valid values: &quot; + minmax[0] + &quot; to &quot; + minmax[1]);
    }, yTxt);

    Y.on(&quot;blur&quot;, function() {
        xHint.set(&quot;innerHTML&quot;, &quot;&quot;);
    }, xTxt);

    Y.on(&quot;blur&quot;, function() {
        yHint.set(&quot;innerHTML&quot;, &quot;&quot;);
    }, yTxt);

    getAll();
});
&lt;&#x2F;script&gt;</pre>

</div>
        </div>

        <div id="sidebar" class="yui3-u">
            

            
                <div class="sidebox">
                    <div class="hd">
                        <h2 class="no-toc">Examples</h2>
                    </div>

                    <div class="bd">
                        <ul class="examples">
                            
                                
                                    <li data-description="Use the Attribute API to define, set and get attribute values.">
                                        <a href="attribute-basic.html">Basic Attribute Configuration</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Configure attributes to be readOnly or writeOnce.">
                                        <a href="attribute-rw.html">Read-Only and Write-Once Attributes</a>
                                    </li>
                                
                            
                                
                                    <li data-description="How to listen for changes in attribute values.">
                                        <a href="attribute-event.html">Attribute Change Events</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Create a basic SpeedDater class, with Attribute support.">
                                        <a href="attribute-basic-speeddate.html">Attribute Based Speed Dating</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Refactors the basic Speed Dating example, to use attribute change events to update rendered elements, and have two instances react to another.">
                                        <a href="attribute-event-speeddate.html">Attribute Event Based Speed Dating</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Add custom methods to get and set attribute values and provide validation support.">
                                        <a href="attribute-getset.html">Attribute Getters, Setters and Validators</a>
                                    </li>
                                
                            
                        </ul>
                    </div>
                </div>
            

            
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

</body>
</html>
